<template>
  <div ref="container" class="slide_nav" @mousewheel="useMouseWheelMove" @scroll="scroll">
    <div ref="navigation" :style="navigationSize" v-if="navigationMode=='thumbnail'">
      <div style="position: relative;" :id="item.id" :ref="item.id" v-for="item in navigationSource" :style="navItem"
           class="img_border" :class="{active:activeItem && item.id==activeItem.id}" @click="activeItem=item "
           @mouseover="mouseOverItem=item.id" @mouseout="mouseOverItem=null">
        <img v-show="mouseOverItem==item.id" src="~@/assets/img/SlideEditor/del.png" class="slide_nav_del"
             @click.stop="SetCatalogueVisible(item.id)" v-if="showMode =='vertical'">
        <img class="slide_nav_img" :src="item.editorThumbnail" draggable="false" v-if="item.editorThumbnail">
        <img class="slide_nav_img" src="~@/assets/img/SlideEditor/Navigation/loading.gif" draggable="false" v-else>
      </div>
    </div>
    <div v-else>
      <el-input placeholder="输入关键字进行过滤" style="width:280px;height:28px;float:left;margin:5px 10px"
                v-model="fileFilterText" size="mini">
      </el-input>
      <el-tree class="filter-tree" highlight-current accordion default-expand-all node-key='ID'
               :data="dossierTreeDataSource" :props="fileProps" :filter-node-method="fileFilterNode"
               style="width:100%;height:360px;overflow:auto" ref="dossier">
      </el-tree>
    </div>
  </div>
</template>
<script>
  import ipcs from '../../common/typeIpcs'
  import action from '../../common/typeActions'
  import commonServer from '../../server/common/commonServer.js'
  // import editorServer from '../../server/slideEditor/editorServer.js'
  import { mapState, mapActions, mapGetters } from 'vuex'

  let scrollBarTimer = null
  let scrollBarState = false
  let scrollBarTime = new Date()

  export default {
    name: 'SlideNavigation',
    props: {
      showMode: { type: String, default: 'vertical' }, // 显示模式
      showCount: { type: Number, default: 5 }, // 显示缩略图数量
      distance: { type: Number, default: 10 }, // 缩略图间隔
      navigationMode: { type: String, default: 'thumbnail' } // 导航模式；thumbnail，tree
    },
    data () {
      return {
        containerSize: null,
        navigationWidth: 0,
        navigationHeight: 0,
        mouseOverItem: null,
        navItem: null,
        isDrawing: false,
        drawItems: [],
        fileFilterText: '',
        fileProps: { children: 'children', label: 'alias' }
      }
    },
    computed: {
      ...mapState({
        isPlay: state => state.slideEditor.isPlay,
        dossiers: state => state.markingAided.pdfFiles,
        catalogData: state => state.preplan.catalogData
      }),
      ...mapGetters(['navigationSource', 'getFilesByID']),
      activeItem: {
        get () {
          return this.$store.state.preplan.activeItem
        },
        set (value) {
          this.$store.dispatch(action.PREPLAN.SET_ACTIVE_NODE, value)
        }
      },
      navigationSize: function () {
        return {
          width: this.navigationWidth ? this.navigationWidth + 'px' : '100%',
          height: this.navigationHeight ? this.navigationHeight + 'px' : '100%'
        }
      }
    },
    mounted () {
      let self = this
      if (!scrollBarTimer) {
        scrollBarTimer = setInterval(() => {
          if (scrollBarState && new Date() - scrollBarTime >= 500) {
            scrollBarState = false
            self.getDisplayImage()
          }
        }, 250)
      }

      // 订阅容器变化消息
      this.$electron.ipcRenderer.on(
        ipcs.RENDERER.navigationSizeSync,
        (ev, arg) => {
          this.calContainerSize(arg)
        }
      )
      this.$electron.ipcRenderer.on(
        ipcs.RENDERER.receiveEditorThumb,
        (ev, arg) => {
          this.isDrawing = false
          this.drawThumbnail()
          this.$store.dispatch(action.PREPLAN.SetSlideThumb, arg)
        }
      )

      this.$nextTick(() => {
        if (
          !this.activeItem &&
          this.navigationSource &&
          this.navigationSource.length
        ) {
          this.activeItem = this.navigationSource[0]
        } else {
          this.calActiveLocation()
        }

        this.getDisplayImage()
      })
    },
    beforeDestroy () {
      if (scrollBarTimer) {
        clearInterval(scrollBarTimer)
        scrollBarTimer = null
      }
    },
    watch: {
      activeItem: async function (n, o) {
        let props = await this.getSlideProps(this.catalogData, n ? n.id : null)
        this.$store.dispatch(action.SLIDEEDITOR.SetSlideProps, props)
        this.calActiveLocation()
        this.rolling(n)
      },
      navigationSource: function (n, o) {
        // if ((!o || !o.length) && n && n.length && !this.activeItem) {
        //     this.activeItem = n[0];
        // }
        if (n.length !== o.length) {
          this.calContainerSize()
        }
      }
    },
    methods: {
      ...mapActions({ SetCatalogueVisible: action.PREPLAN.SetCatalogueVisible }),
      useMouseMove: function () {
        // return
        // let self = this
        // let container = self.$refs.container
        // if (!container) return
        // let location =
        //   self.showMode == 'vertical' ? event.clientY : event.clientX
        // container.onmousemove = () => {
        //   if (self.showMode == 'vertical') {
        //     if (location > event.clientY) {
        //       container.scrollTop += location - event.clientY
        //     } else if (location < event.clientY) {
        //       container.scrollTop -= event.clientY - location
        //     }
        //   } else {
        //     if (location > event.clientX) {
        //       container.scrollLeft += location - event.clientX
        //     } else if (location < event.clientX) {
        //       container.scrollLeft -= event.clientX - location
        //     }
        //   }
        //   location = self.showMode === 'vertical' ? event.clientY : event.clientX
        // }
        // container.onmouseup = () => {
        //   container.onmouseup = container.onmousemove = null
        // }
        // container.onmouseout = () => {
        //   container.onmouseout = container.onmousemove = null
        // }
      },
      useMouseWheelMove: function () {
        let container = this.$refs.container
        if (
          this.navigationMode !== 'thumbnail' ||
          this.showMode !== 'horizontal' ||
          !container
        ) {
          return
        }
        container.scrollLeft -= event.wheelDelta
      },
      drawThumbnail: async function () {
        // 没有待绘项或正在绘制中则终止操作
        if (!this.drawItems.length || this.isDrawing) return
        let slide = await this.getSlideProps(
          this.catalogData,
          this.drawItems[0].id
        )
        this.drawItems.splice(0, 1)
        // 未获取编辑器参数时绘制下一项
        if (!slide) {
          this.drawThumbnail()
          return
        }
        // let files = await this.getSlideImage(slide);
        this.isDrawing = true
        this.$electron.ipcRenderer.send(ipcs.MAIN.generateEditorThumb, {
          slide: slide
        })
      },
      calContainerSize: function (arg) {
        if (this.navigationMode !== 'thumbnail') return
        this.containerSize = arg || this.containerSize
        if (!this.containerSize) return
        if (this.showMode === 'vertical') {
          let itemHeight = this.containerSize.height / this.showCount // 计算图片大小
          this.navigationWidth = 0
          // 容器高度=图片数量*（图片高度+上下边距）+选中边框
          this.navigationHeight =
            this.navigationSource.length * (itemHeight + this.distance * 2) + 4
          this.navItem = {
            // 容器宽度-左右边距-选中边框-滚动条宽度
            width: this.containerSize.width - this.distance * 2 - 4 - 8 + 'px',
            // 显示高度项-显示边框
            height: itemHeight - 2 + 'px',
            float: 'left',
            margin: this.distance + 'px'
          }
        } else {
          let itemWidth = this.containerSize.width / this.showCount
          // 容器宽度=图片数量*（图片宽度+左右边距）+选中边框
          this.navigationWidth =
            this.navigationSource.length * (itemWidth + this.distance * 2) + 4
          this.navigationHeight = 0

          this.navItem = {
            // 显示宽度项-显示边框
            width: itemWidth - 2 + 'px',
            // 容器高度-上下边距-选中边框-滚动条高度
            height: this.containerSize.height - this.distance * 2 - 4 - 8 + 'px',
            float: 'left',
            margin: this.distance + 'px'
          }
        }
      },
      calActiveLocation: function () {
        let container = this.$refs.container
        if (!container || !this.activeItem) return

        let activeItem = this.$refs[this.activeItem.id]
        activeItem = activeItem && activeItem.length > 0 ? activeItem[0] : null
        if (!activeItem) return
        if (this.showMode === 'vertical') {
          container.scrollTop =
            activeItem.offsetTop -
            container.offsetTop +
            activeItem.clientHeight / 2 -
            container.clientHeight / 2
        } else {
          container.scrollLeft =
            activeItem.offsetLeft -
            container.offsetLeft +
            activeItem.clientWidth / 2 -
            container.clientWidth / 2
        }
      },
      // getSlideImage: async function (slide) {
      //     let files = [];
      //     let dataSource = await editorServer.getSlideImages(slide.id, slide.sid);

      //     if (dataSource && dataSource.length) {
      //         dataSource.forEach(item => {
      //             if (item.path) files.push(item.path);
      //         })
      //     }

      //     slide.element.forEach(item => {
      //         if (item.type == "IMAGE" && item.path) files.push(item.path);
      //     });
      //     return this.getFilesByID(files)
      // },
      scroll: function () {
        scrollBarState = true
        scrollBarTime = new Date()
      },
      // 获取容器可视区显示图片
      getDisplayImage: function () {
        if (this.navigationMode !== 'thumbnail') return
        let container = this.$refs.container
        let navigation = this.$refs.navigation
        if (!container || !navigation || !navigation.children) return
        navigation = navigation.children
        let imgCount = this.showCount + 1
        let displayItems = []
        // 查找界面容器可视区显示项
        for (let i = 0; i < navigation.length; i++) {
          if (!imgCount) break
          if (this.showMode === 'vertical') {
            if (navigation[i].offsetTop >= container.scrollTop) {
              imgCount--
              displayItems.push(navigation[i].id)
            }
          } else {
            if (
              navigation[i].offsetLeft >=
              container.scrollLeft +
              container.offsetLeft -
              navigation[i].clientWidth
            ) {
              imgCount--
              displayItems.push(navigation[i].id)
            }
          }
        }
        // 获取渲染项
        this.drawItems = this.navigationSource.filter(x => {
          return displayItems.indexOf(x.id) >= 0 && x.show && !x.editorThumbnail
        })

        // 当没有绘制任务时，绘制可视区显示项
        if (this.drawItems.length && !this.isDrawing) {
          this.drawThumbnail()
        }
      },
      rolling (item) {
        let ref = document.getElementById(item.id + 'play')
        if (ref) {
          ref.scrollIntoView()
          let arr = document.getElementsByClassName('active_backage')
          for (let v of arr) {
            v.classList.remove('active_backage')
          }
          ref.classList.add('active_backage')
        }
      },
      async getSlideProps (dataSource, id) {
        let element = dataSource.find(item => {
          return item.id === id
        })
        if (!element) return null
        let slide = {
          id: element.id,
          sid: element.style
            ? '270e6157-a4fb-6c3a-0a13-c700542f81a9'
            : 'f8dd08bd-22fd-7a19-0206-041893e0e340',
          tid: element.style
            ? 'f69c2dd1-756c-b813-8a7b-152aeaab328e'
            : 'c9427019-3fa2-ed94-b133-55e07457f797',
          element: []
        }
        let parentEl = element.style
          ? null
          : dataSource.find(item => {
            return item.id === element.pid
          })
        let text = element.alias
        if (parentEl) text = `${parentEl.alias}/${text}`

        slide.element.push({
          type: 'TEXT',
          html: text,
          text: text,
          path: ''
        })

        // 当活动项为文件夹时获取该项下所有子节点
        if (element.type === '0') {
          slide.tid = element.template
            ? element.template
            : '76a25261-9855-38e6-cde7-79b7fbf9508b'
          dataSource
            .filter(x => {
              return x.pid === element.id
            })
            .forEach(item => {
              slide.element.push({
                type: 'TEXT',
                orientation: 'top',
                distance: 0.08,
                html: item.alias,
                text: item.alias,
                path: ''
              })
            })
        } else {
          if (!Array.isArray(element.stream)) return slide
          slide.tid = element.template
            ? element.template
            : 'c9427019-3fa2-ed94-b133-55e07457f797'
          for (let i = 0; i < element.stream.length; i++) {
            let id = element.stream[i]
            let fileIDs = await commonServer.getFileIDByCode([id])
            for (let j = 0; j < fileIDs.length; j++) {
              let item = fileIDs[j]
              slide.element.push({
                type: element.fileType,
                orientation: 'left',
                distance: j === 0 ? 0.05 : 0,
                html: '',
                text: '',
                path: item.ID,
                fileID: item.WJID
              })
            }
          }
        }
        return slide
      }
    }
  }
</script>
<style scoped>
  .slide_nav {
    width: 100%;
    height: 100%;
    float: left;
    border: 1px solid #96c7f4;
    overflow: auto;
  }

  .img_border {
    border: 1px solid #ddd;
  }

  .active {
    /* border: 2px solid #157ac1; */
    border: 2px solid #ff0000;
  }

  .slide_nav::-webkit-scrollbar-thumb {
    background-color: #267abb;
    border-radius: 4px;
  }

  .slide_nav::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background: #cbe2ee;
  }

  .slide_nav_img {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  .slide_nav_del {
    position: absolute;
    cursor: pointer;
    top: 5px;
    right: 5px;
  }

  .active_backage {
    background: rgba(26, 132, 197, 0.5);
  }
</style>
